<?php
/**
 *
 *
 */
namespace Yz\modules\Users;
class Controller_ChangePassword
    extends \Yz\modules\Generic\Controller_AbstractUpdate
{

    /**
     *  forbid access unless autenticated
     *
     */
    const ACCESS = \Yz_Access_Interface::AC_VALID_USER;

    protected $model;
    protected $modelName = 'User';
    protected $userInfo;

    /**************************
     *    Protected methods   *
     **************************/


    /**
     *
     */
    protected function fetchData()
    {
        $this->userInfo = \Yz_User_Default::getInstance()->getUserInfo();
        return $this;
    }



    /**
     *  @return this
     *
     */
    protected function updateModel()
    {
        debug();
        if (null === $this->error) {
            $this->selectModel()->updateItemById($this->userInfo);
            $this->success = true;
        }
        return $this;
    }


    /** process the POST input to obtain old and new passwords
     *      Use the following POST arguments:
     *      - oldPassword
     *      - newPassword
     *      - repeatPassword
     *  @param Yz_Hash $post
     *  @return this
     */
    protected function processData(\Yz_Hash $post)
    {
        // prevent verifyPassword from throwing InvalidValueType
        $oldpw = \Yz_String::valueOf($post->oldPassword);
        try {
            // throws user_exception
            $this->userInfo->verifyPassword($oldpw);

            $newpw = \Yz_String::testNotEmpty($post->newPassword);
            $newpw2 = \Yz_String::valueOf($post->repeatPassword);
            if ($newpw2 !== $newpw) {
                throw new \Yz_Exception_InvalidArgument("New passwords do not match");
            }
            $this->userInfo->setPassword($newpw);
        } catch (\Yz_Exception $ex) {
            // TODO modify errorMessage, specifying the reason
            $this->error = $ex;
        }
        return $this;
    }

    /**
     *
     */
    protected function getErrorMessage()
    {
        $msg = parent::getErrorMessage();
        switch (true) {
            case $this->error instanceof \Yz_User_Exception:
                $msg .= ':WrongPassword';
                break;
            case $this->error instanceof \Yz_Exception_InvalidValueType:
            case $this->error instanceof \Yz_Exception_InvalidArgument:
                $msg .= ':PasswordsDontMatch';
                break;
            default:
        }
        return $msg;
    }

}
